package cn.kgc.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Rock
 * @create 2019-11-18 13:58
 */
public class myBatisUtil {
    private static InputStream is;
    private static SqlSessionFactory factory;
    private static  SqlSession session;
    //创建Factory工厂
    public static SqlSessionFactory getFactory() {
        try {
            //1.读取配置文件
            is= Resources.getResourceAsStream("SqlMapConfig.xml");
            //2.创建sqlSessionFactory工厂
            factory=new SqlSessionFactoryBuilder().build(is);
            return factory;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    //生产Session
    public static SqlSession getSession(boolean isAutoCommit) {
        SqlSessionFactory factory=getFactory();
        return factory.openSession(isAutoCommit);
    }

    public void destroy() throws IOException {
        session.close();
        is.close();
    }
}
